<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统主页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .navbar {
            background: rgba(255, 255, 255, 0.95);
            padding: 15px 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar-brand {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
        }

        .navbar-user {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .user-name {
            font-weight: 500;
            color: #333;
        }

        .badge {
            background: #ff9800;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
        }

        .btn-logout {
            padding: 8px 20px;
            border: none;
            border-radius: 8px;
            background: #f44336;
            color: white;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-logout:hover {
            background: #d32f2f;
            transform: translateY(-2px);
        }

        .container {
            max-width: 1200px;
            margin: 40px auto;
            padding: 0 20px;
        }

        .welcome-card {
            background: white;
            border-radius: 16px;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-bottom: 30px;
            text-align: center;
        }

        .welcome-card h1 {
            font-size: 32px;
            color: #333;
            margin-bottom: 10px;
        }

        .welcome-card p {
            color: #666;
            font-size: 16px;
        }

        .cards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: all 0.3s;
            cursor: pointer;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }

        .card-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }

        .card-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }

        .card-desc {
            color: #666;
            font-size: 14px;
        }

        .session-info {
            background: rgba(255, 255, 255, 0.9);
            border-radius: 12px;
            padding: 20px;
            margin-top: 30px;
        }

        .session-info h3 {
            color: #333;
            margin-bottom: 15px;
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .info-item:last-child {
            border-bottom: none;
        }

        .info-label {
            color: #666;
            font-weight: 500;
        }

        .info-value {
            color: #333;
        }

        .status-online {
            color: #4caf50;
            font-weight: bold;
        }

        .admin-only {
            display: none;
        }

        .admin-badge {
            background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: bold;
            position: absolute;
            top: 15px;
            right: 15px;
        }

        .card {
            position: relative;
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="navbar-brand">📊 系统主页</div>
        <div class="navbar-user">
            <div class="user-info">
                <div class="user-avatar" id="userAvatar"></div>
                <div>
                    <div class="user-name" id="userName"></div>
                    <span class="badge" id="userRole"></span>
                </div>
            </div>
            <button class="btn-logout" onclick="logout()">退出登录</button>
        </div>
    </nav>

    <div class="container">
        <div class="welcome-card">
            <h1>🎉 欢迎回来，<span id="welcomeName"></span>！</h1>
            <p>您的登录状态有效期为3小时，有效期内刷新页面不会退出</p>
        </div>

        <div class="cards-grid">
            <!-- 创建用户 - 仅管理员可见 -->
            <div class="card admin-only" id="createUserCard" onclick="window.location.href='create-user.html'">
                <span class="admin-badge">管理员</span>
                <div class="card-icon">👤</div>
                <div class="card-title">创建用户</div>
                <div class="card-desc">创建管理员或子管理员</div>
            </div>

            <!-- 用户管理 - 仅管理员可见 -->
            <div class="card admin-only" id="userManagementCard" onclick="window.location.href='user-management.html'">
                <span class="admin-badge">管理员</span>
                <div class="card-icon">👥</div>
                <div class="card-title">用户管理</div>
                <div class="card-desc">管理、删除、授权用户</div>
            </div>

            <!-- 数据导入 - 仅管理员可见 -->
            <div class="card admin-only" id="dataImportCard" onclick="window.location.href='data-import.html'">
                <span class="admin-badge">管理员</span>
                <div class="card-icon">📊</div>
                <div class="card-title">数据导入</div>
                <div class="card-desc">Excel批量导入数据</div>
            </div>

            <!-- 修改密码 - 所有用户可见 -->
            <div class="card" onclick="window.location.href='change-password.html'">
                <div class="card-icon">🔒</div>
                <div class="card-title">修改密码</div>
                <div class="card-desc">修改您的登录密码</div>
            </div>

            <!-- API文档 - 所有用户可见 -->
            <div class="card" onclick="window.location.href='doc.html'">
                <div class="card-icon">📖</div>
                <div class="card-title">API文档</div>
                <div class="card-desc">查看接口文档</div>
            </div>

            <!-- 预警调试 - 所有用户可见 -->
            <div class="card" onclick="openWarningDebug()">
                <div class="card-icon">🔔</div>
                <div class="card-title">预警调试</div>
                <div class="card-desc">WebSocket预警测试工具</div>
            </div>

            <!-- 系统设置 - 所有用户可见 -->
            <div class="card">
                <div class="card-icon">⚙️</div>
                <div class="card-title">系统设置</div>
                <div class="card-desc">配置系统参数</div>
            </div>

            <!-- 用户管理 - 所有用户可见 -->
            <div class="card">
                <div class="card-icon">👥</div>
                <div class="card-title">用户管理</div>
                <div class="card-desc">管理系统用户</div>
            </div>
        </div>

        <div class="session-info">
            <h3>🔐 会话信息</h3>
            <div class="info-item">
                <span class="info-label">用户名：</span>
                <span class="info-value" id="infoUsername"></span>
            </div>
            <div class="info-item">
                <span class="info-label">用户ID：</span>
                <span class="info-value" id="infoUserId"></span>
            </div>
            <div class="info-item">
                <span class="info-label">角色：</span>
                <span class="info-value" id="infoRole"></span>
            </div>
            <div class="info-item">
                <span class="info-label">Token状态：</span>
                <span class="info-value status-online" id="infoStatus">✅ 在线</span>
            </div>
            <div class="info-item">
                <span class="info-label">Token有效期：</span>
                <span class="info-value">3小时</span>
            </div>
        </div>
    </div>

    <script>
        const API_BASE_URL = '/api/user';

        // 页面加载时验证token
        window.addEventListener('DOMContentLoaded', async () => {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            const userId = localStorage.getItem('userId');
            const administrator = localStorage.getItem('administrator');

            if (!token) {
                // 没有token，跳转到登录页
                window.location.href = 'login.html';
                return;
            }

            try {
                // 验证token是否有效
                const response = await fetch(`${API_BASE_URL}/validate`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });

                const result = await response.json();

                if (result.code === 200) {
                    // Token有效，显示用户信息
                    const isAdmin = administrator === 'true' || administrator === '1';
                    displayUserInfo(username, userId, isAdmin);
                } else {
                    // Token无效，清除并跳转到登录页
                    localStorage.clear();
                    alert('登录已过期，请重新登录');
                    window.location.href = 'login.html';
                }

            } catch (error) {
                console.error('验证失败:', error);
                localStorage.clear();
                alert('验证失败，请重新登录');
                window.location.href = 'login.html';
            }
        });

        // 显示用户信息
        function displayUserInfo(username, userId, isAdmin) {
            const firstLetter = username.charAt(0).toUpperCase();
            
            // 获取用户级别 0=子管理员 1=管理员 2=总管理员
            const userLevel = parseInt(localStorage.getItem('userLevel') || localStorage.getItem('administrator') || 0);
            let roleName;
            if (userLevel >= 2) {
                roleName = '总管理员';
            } else if (userLevel == 1) {
                roleName = '管理员';
            } else {
                roleName = '子管理员';
            }

            document.getElementById('userAvatar').textContent = firstLetter;
            document.getElementById('userName').textContent = username;
            document.getElementById('userRole').textContent = roleName;
            document.getElementById('welcomeName').textContent = username;
            
            document.getElementById('infoUsername').textContent = username;
            document.getElementById('infoUserId').textContent = userId;
            document.getElementById('infoRole').textContent = roleName;

            // 根据用户角色显示/隐藏管理员专用功能
            // 管理员(1)及以上可以看到管理功能
            if (userLevel >= 1) {
                // 显示管理员专用卡片
                const adminCards = document.querySelectorAll('.admin-only');
                adminCards.forEach(card => {
                    card.style.display = 'block';
                });
                console.log('管理员用户（级别：' + userLevel + '），显示所有功能');
            } else {
                // 隐藏管理员专用卡片
                const adminCards = document.querySelectorAll('.admin-only');
                adminCards.forEach(card => {
                    card.style.display = 'none';
                });
                console.log('子管理员，隐藏管理员功能');
            }
        }

        // 登出
        async function logout() {
            if (!confirm('确定要退出登录吗？')) {
                return;
            }

            const token = localStorage.getItem('token');

            try {
                const response = await fetch(`${API_BASE_URL}/logout`, {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });

                const result = await response.json();

                if (result.code === 200) {
                    localStorage.clear();
                    alert('✅ 退出成功');
                    window.location.href = 'login.html';
                } else {
                    alert('❌ 退出失败：' + result.message);
                }

            } catch (error) {
                console.error('退出失败:', error);
                // 即使请求失败，也清除本地存储并跳转
                localStorage.clear();
                window.location.href = 'login.html';
            }
        }

        // 定期检查token有效性（每5分钟）
        setInterval(async () => {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
                return;
            }

            try {
                const response = await fetch(`${API_BASE_URL}/validate`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });

                const result = await response.json();

                if (result.code !== 200) {
                    // Token过期
                    localStorage.clear();
                    alert('🔔 登录已过期，请重新登录');
                    window.location.href = 'login.html';
                }

            } catch (error) {
                console.error('Token验证失败:', error);
            }
        }, 5 * 60 * 1000); // 5分钟检查一次

        // 打开预警调试页面（携带token）
        function openWarningDebug() {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('❌ 未找到登录Token，请重新登录');
                window.location.href = 'login.html';
                return;
            }
            
            // 跳转到ws-debug.html并携带token参数
            window.location.href = `ws-debug.html?token=${token}`;
        }
    </script>
</body>
</html>

